package cn.rengy.tpa.wxmp.oauth;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.Consts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 网站应用微信登录
 * <p>
 * 参考<a href=
 * "https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=b9570d3ae36a604ea88b6aeab286f693f604bffd&lang=zh_CN">开发文档</a>
 * </p>
 */
public class WebOAuth2Api {

	private static Logger logger = LoggerFactory.getLogger(WebOAuth2Api.class);


	private static final String OAUTH2_WEB_GET_CODE="https://open.weixin.qq.com/connect/qrconnect";
	
	public static final String SCOPE = "snsapi_login";
		
		
	/**
	 * 生成OAuth重定向URI（用户同意授权，获取code）
	 * @param appid
	 * @param redirectURI
	 * @param state
	 * @return
	 */
	public static String generateRedirectURI(String appid,String redirectURI, String state) {
		StringBuffer url = new StringBuffer();
		url.append(OAUTH2_WEB_GET_CODE);
		url.append("?appid=").append(appid);
		url.append("&redirect_uri=").append(urlEncode(redirectURI));
		url.append("&response_type=code");
		url.append("&scope=").append(SCOPE);
		url.append("&state=").append(urlEncode(state));
		url.append("#wechat_redirect");
		return url.toString();
	}

	public static void main(String args[]) {
		System.out.println(generateRedirectURI("wx314cf8de2e542cf5","http://www.liechang999.com", ""));
	}
	

	/**
	 * 使用UTF-8进行URL编码
	 *
	 * @param str
	 * @return
	 */
	private static String urlEncode(String str) {
		String result = null;
		try {
			result = URLEncoder.encode(str, Consts.UTF_8.name());
		} catch (UnsupportedEncodingException e) {
			// never throws
		}
		return result;
	}

	

}
